import React, { PureComponent, Fragment } from 'react';
import { Table, Alert, Badge, Divider, Modal } from 'antd';
import { connect } from 'dva';
import styles from './index.less';

const statusMap = ['success', 'error'];

@connect(({ RecommendResult, loading }) => ({
  RecommendResult,
  loading: loading.models.RecommendResult,
}))
class RecommendResultTable extends PureComponent {
  static smartTypes = [
    { text: '结果1（撞库通过）', value: 1 },
    { text: '结果2（条件筛选）', value: 2 },
    { text: '结果3（筛选无结果）', value: 3 },
  ];
  state = {
    selectedRowKeys: [],
    totalCallNo: 0,
  };

  componentWillReceiveProps(nextProps) {
    // clean state
    if (nextProps.selectedRows.length === 0) {
      this.setState({
        selectedRowKeys: [],
        totalCallNo: 0,
      });
    }
  }

  handleRowSelectChange = (selectedRowKeys, selectedRows) => {
    const totalCallNo = selectedRows.reduce((sum, val) => {
      return sum + parseFloat(val.callNo, 10);
    }, 0);

    if (this.props.onSelectRow) {
      this.props.onSelectRow(selectedRows);
    }

    this.setState({ selectedRowKeys, totalCallNo });
  }

  handleTableChange = (pagination, filters, sorter) => {
    this.props.onChange(pagination, filters, sorter);
  }

  cleanSelectedKeys = () => {
    this.handleRowSelectChange([], []);
  }

  deleteOne = (id) => {
    const { dispatch } = this.props;
    const that = this;
    Modal.confirm({
      title: '删除警告!',
      content: '确认删除所选内容？',
      onOk() {
        dispatch({
          type: 'recommend/remove',
          payload: {
            types: `${id},`,
          },
          callback: () => {
            that.setState({
              selectedRows: [],
            });
          },
        });
      },
      onCancel() {
        // alert(JSON.stringify(selectedRows));
      },
    });
  }

  // 修改
  modifyOne = (row) => {
    this.props.modifyOne(row, true);
  }

  render() {
    const { selectedRowKeys, totalCallNo } = this.state;
    const { data: { list, pagination }, loading } = this.props;

    const columns = [
      {
        title: '结果类型',
        dataIndex: 'type',
        render: (val) => {
          // eslint-disable-next-line camelcase
          const smart_Types = RecommendResultTable.smartTypes;
          let result = '';
          smart_Types.every((type) => {
            if (type.value === val) {
              result = type.text;
              return false;
            }
            return true;
          });
          return `${result}`;
        },
      },
      {
        title: '匹配度',
        dataIndex: 'matchPercent',
      },
      {
        title: '描述',
        dataIndex: 'desc',
      },
      {
        title: '编辑人',
        dataIndex: 'uid',
      },
      {
        title: '编辑时间',
        dataIndex: 'editTime',
      },
      /*  {
        title: '更新时间',
        dataIndex: 'updatedAt',
        sorter: true,
        render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
      },  */
      {
        title: '操作',
        render: (val, row) => {
          return (
            <Fragment>
              <a onClick={() => this.modifyOne(row)}>修改</a>
              <Divider type="vertical" />
              <a onClick={() => this.deleteOne(row.type)}>删除</a>
            </Fragment>
          );
        },
      },
    ];

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
    };

    const rowSelection = {
      selectedRowKeys,
      onChange: this.handleRowSelectChange,
      getCheckboxProps: record => ({
        disabled: record.disabled,
      }),
    };

    return (
      <div className={styles.standardTable}>
        <div className={styles.tableAlert}>
          <Alert
            message={(
              <div>
                已选择 <a style={{ fontWeight: 600 }}>{selectedRowKeys.length}</a> 项&nbsp;&nbsp;
                <a onClick={this.cleanSelectedKeys} style={{ marginLeft: 24 }}>清空</a>
              </div>
            )}
            type="info"
            showIcon
          />
        </div>
        <Table
          className={styles.tableTr}
          loading={loading}
          rowKey={record => record.key}
          rowSelection={rowSelection}
          dataSource={list}
          columns={columns}
          pagination={paginationProps}
          onChange={this.handleTableChange}
        />
      </div>
    );
  }
}

export default RecommendResultTable;
